<template>
  <div style="margin-top: 50px">
    <el-form
      ref="productInfoForm"
      :model="value"
      :rules="rules"
      label-width="120px"
      inline
      style="width: 100%;height: 100%"
    >
      <el-col :span="12">
        <el-form-item label="產品編號：">
          <el-input v-model="value.sku" type="text" class="paperview-input-text" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="条形码编号：">
          <el-input v-model="value.upc" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="中文商品名称：" prop="nameCn">
          <el-input v-model="value.nameCn" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="英文商品名称：" prop="nameEn">
          <el-input v-model="value.nameEn" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="中文详细标题：">
          <el-input v-model="value.detailTitleCn" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="英文详细标题：">
          <el-input v-model="value.detailTitleEn" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品分类：" prop="productCategoryId">
          <el-cascader
            ref="cascader"
            v-model="selectProductCateValue"
            :options="productCateOptions"
            style="width: 360px;"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品品牌：">
          <el-select
            v-model="value.brandId"
            placeholder="请选择品牌"
            style="width: 360px;"
            @change="handleBrandChange"
          >
            <el-option
              v-for="item in brandOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="24">
        <el-form-item label="輔助分類關鍵詞">
          <el-select
            v-model="keyWord"
            placeholder="请选择關鍵詞"
            style="width: 360px;"
            filterable
            @change="handleKeyWordChange"
          >
            <el-option
              v-for="item in keyWordList"
              :key="item.id"
              :label="item.nameCn"
              :value="{ keyWordCn:item.nameCn, keyWordEn:item.nameEn }"
            />
          </el-select>
          <el-tag
            v-for="tag in value.keyWordCn"
            :key="tag"
            closable
            style="margin-right: 5px"
            @close="delKeyword(tag)"
          > {{ tag }}</el-tag>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="正常售價：" prop="originalPrice">
          <el-input v-model.number="value.originalPrice" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品重量：">
          <el-input v-model="value.weight" style="width: 360px" placeholder="默认重量单位为克" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="優惠價：">
          <el-input v-model.number="value.price" style="width: 360px" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="虚拟已售数量：">
          <el-input v-model.number="value.sale" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="排序">
          <el-input-number v-model="value.sort" label="描述文字" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="積分兌換:">
          <el-input-number v-model="value.integral" label="0代表不是積分商品" />
          <div style="color: #c0c4d8">0代表不可以使用積分兌換</div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="商品备注：">
          <el-input v-model="value.note" type="textarea" :auto-size="true" style="width: 360px" />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="商品上架：">
          <el-switch
            v-model="value.publishStatus"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="膠袋收費：">
          <el-switch
            v-model="value.bagFeeStatus"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="是否預定：">
          <el-switch
            v-model="value.predestine"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="value.predestine" :span="8">
        <el-form-item label="配送方案：">
          <el-select
            v-model="value.deliverSetId"
            placeholder="请选择配送方案"
            style="width: 220px;"
            @change="handleBrandChange"
          >
            <el-option
              v-for="item in deliverSet"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24" :offset="10">
        <el-form-item style="text-align: center">
          <el-button type="primary" size="medium" @click="handleNext('productInfoForm')">下一步，填写商品属性</el-button>
        </el-form-item>
      </el-col>

    </el-form>
  </div>
</template>

<script>
import { getTree } from '@/api/pms/productCategory'
import { getAll } from '@/api/pms/brand'
import keyWord from '@/api/pms/keyWord'
import { findAll } from '@/api/sms/deliverSet'

export default {
  name: 'ProductInfoDetail',
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  dicts: [],
  data() {
    return {
      hasEditCreated: false,
      // 选中商品分类的值
      selectProductCateValue: [],
      productCateOptions: [],
      brandOptions: [],
      deliverSet: [],
      keyWordList: [],
      keyWordCn: [],
      keyWord: '',
      rules: {
        nameCn: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
        ],
        nameEn: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' }
        ],
        subTitle: [{ required: true, message: '请输入商品副标题', trigger: 'blur' }],
        productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品介绍', trigger: 'blur' }],
        requiredProp: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        sku: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        upc: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        originalPrice: [{ required: true, message: '该项为必填且為數字', trigger: 'blur', type: 'number' }]
      }
    }
  },
  computed: {
    // 商品的编号
    productId() {
      return this.value.id
    }
  },
  watch: {
    productId: function(newValue) {
      if (!this.isEdit) return
      if (this.hasEditCreated) return
      if (newValue === undefined || newValue == null || newValue === 0) return
      this.handleEditCreated()
    },
    selectProductCateValue: function(newValue) {
      if (newValue != null && newValue.length === 2) {
        this.value.productCategoryId = newValue.slice(-1).join()
        this.value.productCategoryName = this.getCateNameById(this.value.productCategoryId)
      } else {
        this.value.productCategoryId = null
        this.value.productCategoryName = null
      }
    }
  },
  created() {
    this.getProductCateList()
    this.getBrandList()
    this.getKeyWordList()
    this.getDeliverSet()
  },
  methods: {
    // 处理编辑逻辑
    handleEditCreated() {
      if (this.value.productCategoryId != null) {
        this.selectProductCateValue.push(this.value.productCategory.parentId)
        this.selectProductCateValue.push(this.value.productCategoryId)
      }
      this.hasEditCreated = true
    },
    /* 獲取配送方案 */
    getDeliverSet() {
      findAll({ deliverType: 0 }).then(res => {
        if (res.code === 0) {
          this.deliverSet = res.data
        }
      })
    },
    /* 获取商品分类树形*/
    getProductCateList() {
      getTree().then(response => {
        const list = response.data
        this.productCateOptions = []
        for (let i = 0; i < list.length; i++) {
          const children = []
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ value: list[i].children[j].id, label: list[i].children[j].label })
            }
          }
          this.productCateOptions.push({ value: list[i].id, label: list[i].label, children: children })
        }
      })
    },
    /* 獲取關鍵詞列表*/
    getKeyWordList() {
      keyWord.all().then(res => {
        this.keyWordList = res.data
      })
    },
    /* 獲取品牌分類列表*/
    getBrandList() {
      getAll().then(response => {
        this.brandOptions = []
        const brandList = response.data
        for (let i = 0; i < brandList.length; i++) {
          this.brandOptions.push({ label: brandList[i].nameCn, value: brandList[i].id })
        }
      })
    },
    getCateNameById(id) {
      let name = null
      for (let i = 0; i < this.productCateOptions.length; i++) {
        for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
          /* eslint-disable */
          if (this.productCateOptions[i].children[j].value == id) {
            name = this.productCateOptions[i].children[j].label
            this.$refs['cascader'].inputValue = name
            return name
          }
        }
      }
      return name
    },
    handleNext(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit('nextStep')
        }
      })
    },
    handleBrandChange(val) {
      let brandName = ''
      for (let i = 0; i < this.brandOptions.length; i++) {
        if (this.brandOptions[i].value === val) {
          brandName = this.brandOptions[i].label
          break
        }
      }
      this.value.brandName = brandName
    },
    handleKeyWordChange(val) {
      if ( this.value.keyWordCn.includes(val.keyWordCn)) {
        this.$message.error('該關鍵詞已經添加,請勿重複添加');
      }else{
        this.value.keyWordCn.push(val.keyWordCn)
        this.value.keyWordEn.push(val.keyWordEn)

      }
      this.keyWord = ''
    },
    delKeyword(tag) {
      this.value.keyWordCn.splice( this.value.keyWordCn.findIndex(item => item === tag), 1)
      for (let i = 0; i < this.keyWordList.length; i++) {
        if(this.keyWordList[i].nameCn === tag) {
          this.value.keyWordEn.splice( this.value.keyWordEn.findIndex(item => item ===  this.keyWordList[i].nameEn), 1)
          return
        }
      }
    }
  }
}
</script>

<style scoped>
.paperview-input-text >>> .el-input__inner {
  -webkit-appearance: none;
  background-color: #FFF;
  background-image: none;
  border-radius: 4px;
  border: 0px;
}
</style>
